package com.hello.booksale.filter;

import com.hello.booksale.entity.RoleEntity;
import com.hello.booksale.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Objects;

@Slf4j
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
    private JwtUtil jwtUtil;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {
        super(authenticationManager);
        this.jwtUtil = jwtUtil;

    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("在JWT过滤器中的url: {}",request.getRequestURI());

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                if (Objects.equals(cookie.getName(), "token")) {
                    log.info("token的值是: {}", cookie.getValue());
                    if (cookie.getValue() != null && !cookie.getValue().isEmpty()) {
                        String token = cookie.getValue();
                        boolean isTokenExpired = false;
                        isTokenExpired = jwtUtil.isTokenExpired(jwtUtil.getExpiration(token));
                        if (isTokenExpired) {
                            cookie.setValue(null);
                            cookie.setMaxAge(0);
                            cookie.setPath("/");
                            response.addCookie(cookie);
                            response.sendRedirect("/login");
                            logger.info("token已失效");
                            return;
                        }
                        String userName = jwtUtil.getUsername(token);
                        UsernamePasswordAuthenticationToken authenticationToken;
                        if (Objects.equals(userName, "admin")) {
                            authenticationToken = new UsernamePasswordAuthenticationToken(userName, null, Collections.singletonList(new RoleEntity("ROLE_admin")));
                        } else {
                            authenticationToken = new UsernamePasswordAuthenticationToken(userName, null, Collections.singletonList(new RoleEntity("ROLE_user")));
                        }
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                    break;
                }
            }
        }
        log.info("通过的是: JWTAuthenticationFilter");
        chain.doFilter(request, response);
    }
}
